package ar.com.miguelgriffa.secureproperties.ant;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;

import ar.com.miguelgriffa.secureproperties.SecureProperties;

public class BaseTask extends Task {
	protected File plain;

	protected File secure;

	protected boolean overwrite = false;

	protected boolean verify = true;
	
	protected String header = "Generated by SecureProperties ANT Task";

	protected String key = null;
	
	protected List<FileSet> filesets = new ArrayList<FileSet>();

	protected boolean failOnError = true;
	
	public String getHeader() {
		return header;
	}

	public void setHeader(String header) {
		this.header = header;
	}

	public boolean isOverwrite() {
		return overwrite;
	}

	public void setOverwrite(boolean overwrite) {
		this.overwrite = overwrite;
	}

	public File getPlain() {
		return plain;
	}

	public void setPlain(File plain) {
		this.plain = plain;
	}

	public File getSecure() {
		return secure;
	}

	public void setSecure(File secure) {
		this.secure = secure;
	}

	public boolean isVerify() {
		return verify;
	}

	public void setVerify(boolean verify) {
		this.verify = verify;
	}


	/**
	 * Ensure the given plain file matches properties and values with given secure file or throw a build exception
	 * 
	 * @param plain
	 * @param secure
	 */
	protected void verify(File plain, File secure) {
		try {
			FileInputStream plainInput = new FileInputStream(plain);
			FileInputStream secureInput = new FileInputStream(secure);
			
			Properties plainProperties = new Properties();
			SecureProperties secureProperties = new SecureProperties();
			
			if (key!=null) {
				secureProperties.setKey(key);
			}
			
			plainProperties.load(plainInput);
			secureProperties.load(secureInput);
			
			if (plainProperties.equals(secureProperties)) {
				log("Plain and secure files verified");
			} else {
				throw new BuildException("Plain and secure properties do not match, if you can consistenly reproduce this please report it at http://code.google.com/p/secureproperties/issues/entry");
			}
			
		} catch (BuildException e) {
			throw e;
		} catch (Exception e) {
			throw new BuildException(e);
		}
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public void addFileset(FileSet fileset) {
		this.filesets.add(fileset);
	}
	

	protected void handleException(Exception e) throws BuildException {
		if (this.failOnError) { 
			if (e instanceof BuildException)
				throw (BuildException)e;
			throw new BuildException(e);
		} else {
			log("ERROR: "+e);
		}
	}

	public boolean isFailOnError() {
		return failOnError;
	}

	public void setFailOnError(boolean failOnError) {
		this.failOnError = failOnError;
	}
}
